﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CarbonExchange.Bll
{
    public class OffsettingCostFactory : FactoryBase<OffsettingCost>
    {
        protected override void MarkItemForDeletion(OffsettingCost item)
        {
            throw new NotImplementedException();
        }

        protected override void Validate(IQueryable<OffsettingCost> items, CarbonExchange.Bll.Exceptions.ValidationException exp)
        {
            foreach (var item in items)
            {
                Validate(item, exp);
            }
        }

        private void Validate(OffsettingCost item, CarbonExchange.Bll.Exceptions.ValidationException exp)
        {
            if (item.Cost <= 0)
            {
                exp.Add("Cost must be greater than 0");
            }
        }

        protected override void PopulateDataChanges(OffsettingCost item, object dataItem)
        {
            var data = (Dal.OffsettingCost)dataItem;
            if (item.Id == 0)
            {
                item.Id = data.Id;
            }
            item.CID = data.CID;
        }


        protected override object GetDataItemForUpdate(OffsettingCost item)
        {
            return Convert(item);
        }

        private Dal.OffsettingCost Convert(OffsettingCost item)
        {
            Dal.OffsettingCost data = null;
            if (item.Id > 0)
            {
                data = DalContext.OffsettingCosts.Single(offsettingCost => offsettingCost.Id == item.Id);
            }
            else
            {
                data = new CarbonExchange.Dal.OffsettingCost();
                DalContext.OffsettingCosts.InsertOnSubmit(data);
            }
            data.Cost = item.Cost;
            return data;
        }

        public OffsettingCost Get()
        {
            OffsettingCost item = Convert(DalContext.OffsettingCosts.FirstOrDefault());
            if (item == null)
                item = new OffsettingCost();
            return item;
        }

        private OffsettingCost Convert(CarbonExchange.Dal.OffsettingCost data)
        {
            if (data != null)
            {
                return new OffsettingCost()
                {
                    Id = data.Id,
                    Cost = data.Cost,
                    CID = data.CID
                };
            }
            else
            {
                return null;
            }
        }
    }
}
